package com.enzoism.springboot.dive.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.enzoism.springboot.dive.constants.StudyConstant.STUDY_BIS_TYPE;

/**
 * 给容器中注入一个RestHighLevelClient
 */
@Configuration
public class ElasticSearchConfig {
    @Autowired
    private ESConfig esConfig;

    @Bean
    public RestHighLevelClient esRestClient() {
//        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
//                //在这里配置你的elasticsearch的情况
//                new HttpHost("127.0.0.1", 9200, "http")));
//        return client;
        // 读取YAML配置信息
        ESConfig.Config config = esConfig.getConfigs().get(STUDY_BIS_TYPE);

        // 配置host/port/username/password信息
        String[] hosts = config.getHost().split(",");
        String[] ports = config.getPort().split(",");
        HttpHost[] httpHostList = new HttpHost[hosts.length];
        for (int i = 0; i < hosts.length; i++) {
            httpHostList[i] = new HttpHost(hosts[i], Integer.parseInt(ports[i]), "http");
        }
        // 创建client
        return new RestHighLevelClient(RestClient.builder(httpHostList));
    }
}
